package com.ruoyi.heytalk.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.annotation.DataSource;
import com.ruoyi.common.constant.heytalk.CommonConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.heytalk.ImFriend;
import com.ruoyi.common.core.domain.heytalk.ImGroup;
import com.ruoyi.common.core.domain.heytalk.ImGroupUser;
import com.ruoyi.common.core.domain.heytalk.ImUser;
import com.ruoyi.common.core.domain.heytalk.dto.CreateGroupDTO;
import com.ruoyi.common.core.domain.heytalk.netty.ChatMsg;
import com.ruoyi.common.core.domain.heytalk.vo.LoginImUser;
import com.ruoyi.common.core.mybatisplus.core.ServicePlusImpl;
import com.ruoyi.common.core.service.HeyTalkTokenService;
import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.heytalk.mapper.ImGroupMapper;
import com.ruoyi.heytalk.netty.IChatForwardHandlerService;
import com.ruoyi.heytalk.service.IImFriendService;
import com.ruoyi.heytalk.service.IImGroupService;
import com.ruoyi.heytalk.service.IImGroupUserService;
import com.ruoyi.heytalk.service.IImUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 群组Service业务层处理
 * 
 * @author zhusy
 * @since 2021-10-17
 */
@Service
@DataSource(value = DataSourceType.SLAVE)
public class ImGroupServiceImpl extends ServicePlusImpl<ImGroupMapper, ImGroup, ImGroup> implements IImGroupService {

    @Resource
    private HeyTalkTokenService tokenService;

    @Resource
    private IImFriendService friendService;

    @Resource
    private IImUserService userService;

    @Resource
    private IImGroupUserService groupUserService;

    @Resource
    private IChatForwardHandlerService chatForwardHandlerService;

    @Override
    @Transactional
    public AjaxResult<Void> createGroup(CreateGroupDTO createGroupDTO) {
        try {
            LoginImUser loginImUser = tokenService.getLoginImUser(ServletUtils.getRequest());
            ImUser imUser = loginImUser.getUser();
            //验证是否是我的好友
            List<ImFriend> friendList = friendService.list(new LambdaQueryWrapper<ImFriend>()
                    .eq(ImFriend::getUserId, loginImUser.getUserId())
                    .in(ImFriend::getFriendId, createGroupDTO.getIds()));
            if (friendList.isEmpty()) {
                return AjaxResult.error("请选择需要加入群聊的好友", null);
            }
            ImGroup imGroup = ImGroup.builder()
                    .name(CommonConstants.GROUP_NAME + CommonConstants.PLUS + DateUtil.now() + CommonConstants.PLUS + imUser.getNickName())
                    .userId(loginImUser.getUserId()).build();
            boolean groupFlag = this.save(imGroup);
            if (!groupFlag) {
                throw new ServiceException("创建群组失败，请联系管理员");
            }
            List<ImUser> userList = userService.list(new LambdaQueryWrapper<ImUser>().in(ImUser::getId, createGroupDTO.getIds()));
            userList.add(imUser);
            List<ImGroupUser> groupUserList = userList.stream().map(
                    user-> {return ImGroupUser.builder()
                            .userId(user.getId())
                            .groupId(imGroup.getId())
                            .nickName(StrUtil.isNotBlank(user.getNickName()) ? user.getNickName() : user.getUserName())
                            .build();}).collect(Collectors.toList());
            if (groupUserList.isEmpty()) {
                return AjaxResult.error("请选择需要加入群聊的好友", null);
            }
            if (!groupUserService.saveBatch(groupUserList)) {
                throw new ServiceException("创建群组用户失败，请联系管理员");
            }
            List<String> userIdList = groupUserList.stream().map(ImGroupUser::getUserId).collect(Collectors.toList());
            chatForwardHandlerService.chat(userIdList, CommonConstants.DataTypeEnum.CHAT.getCode(), true, false, ChatMsg.builder()
                    .id(IdUtil.fastSimpleUUID())
                    .fromAvatar(imUser.getAvatar())
                    .fromId(loginImUser.getUserId())
                    .fromName(StrUtil.isNotBlank(imUser.getNickName())? imUser.getNickName() : imUser.getUserName())
                    .toId(imGroup.getId())
                    .toName(imGroup.getName())
                    .toAvatar(imGroup.getAvatar())
                    .chatType(CommonConstants.ChatTypeEnum.GROUP_CHAT.getCode())
                    .type(CommonConstants.DataTypeEnum.SYSTEM.getCode())
                    .data(CommonConstants.GROUP_SUCCESS_MSG)
                    .isRemove(CommonConstants.IsRemoveEnum.ZERO.getCode())
                    .group(imGroup)
                    .build());
            return AjaxResult.success();
        } catch (ServiceException e) {
            throw new ServiceException(e.getMessage());
        } catch (Exception e) {
            throw new ServiceException("创建群聊失败，请联系管理员");
        }
    }

}
